﻿using Batman.Cache.Attributes;
using Batman.Cache.Extensions;
using Batman.Cache.Helpers.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Batman.Cache.Helpers
{
    public class CacheUsageHelper
    {
        public static List<CacheUsageDto> GetCacheMap()
        {
            var types = Assembly.GetCallingAssembly().ExportedTypes;

            var cacheClasses = types.Where(t => typeof(ICacheWorkable).IsAssignableFrom(t)).ToList();

            var results = new List<CacheUsageDto>();

            foreach (var cacheClass in cacheClasses)
            {
                var methods = cacheClass.GetMembers().Where(t => t.GetCustomAttributes(typeof(CacherAttribute)).Any()).ToList();

                foreach (var method in methods)
                {
                    var cachers = method.GetCustomAttributes(typeof(CacherAttribute)).OfType<CacherAttribute>();
                    var methodName = $"{cacheClass.Namespace}.{cacheClass.Name}.{method.Name}";

                    foreach (var cacher in cachers)
                    {
                        if (cacher.CacherType == CacherType.Cache && string.IsNullOrEmpty(cacher.Id))
                            cacher.Id = methodName;

                        results.Add(new CacheUsageDto
                        {
                            Cacher = cacher,
                            MethodComment = method.GetSummary(),
                            MethodName = methodName
                        });
                    }
                }
            }

            return results;
        }
    }
}